package com.xinyue.server.framework.handler;

import com.xinyue.server.framework.common.GameFrameworkConfig;
import com.xinyue.server.framework.common.GameServerUtil;
import com.xinyue.server.framework.handlermapping.GameCacheModel;
import com.xinyue.server.framework.handlermapping.GameServerCacheService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

public class GameChannelConfirmHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(GameChannelConfirmHandler.class);
    @Autowired
    private GameFrameworkConfig gameFrameworkConfig;
    @Autowired
    private GameServerCacheService gameServerCacheService;

    private Future<?> future;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String channelId = GameServerUtil.getChannelId(ctx.channel());
        logger.info("连接成功,等待连接认证...，channelId: {}", channelId);
        // 添加一个延时任务，过一段时间之后，判断是否认证成功，如果认证成功了，gameChannel一定不会为空
        future = ctx.channel().eventLoop().schedule(() -> {
            GameCacheModel gameCacheModel = gameServerCacheService.getGameCacheModel(ctx);
            if (gameCacheModel == null) {
                logger.warn("连接未认证成功，主动断开连接，channelId:{}", channelId);
                ctx.close();
            } else {
                logger.info("连接认证成功!!");
            }
        }, gameFrameworkConfig.getConfirmTimeout(), TimeUnit.SECONDS);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (future != null && future.isCancellable()) {
            logger.debug("连被关闭，取消连接通道认证的延迟任务,channelId:{}", GameServerUtil.getChannelId(ctx.channel()));
            future.cancel(true);
        }
        ctx.fireChannelInactive();
    }
}
